'use strict';

const Controller = require('egg').Controller;
const crypto = require('crypto');

class HomeController extends Controller {

  async getUserInfoByVideo() {
    const {
      ctx,
      app
    } = this;

    const {
      QueryTypes
    } = require('sequelize');

    const {
      id = -1
    } = ctx.query;

    const data = await app.model.query(
      'SELECT * FROM `info` WHERE `user_id` = (SELECT publisher_id FROM video WHERE id = :id)', {
        replacements: {
          id
        },
        type: QueryTypes.SELECT
      }
    );

    ctx.response.body = {
      code: 200,
      msg: 'The query is successful !',
      data:data[0]
    }


  }

  async getInfo() {
    const {
      ctx,
      app
    } = this;
    var userId = ctx.userInfo.id
    //获取用户id
    const info = await ctx.model.Info.findOne({
      where: {
        user_id: userId
      }
    })

    ctx.response.body = {
      code: 200,
      msg: 'The query is successful !',
      data: {
        info
      }
    }
  }

  async changeInfo() {
    const {
      ctx,
      app
    } = this;

    var userId = ctx.userInfo.id
    const {
      nickname,
      introduction,
      imgUrl
    } = ctx.request.body;

    if (nickname != '' && introduction != '') {
      await ctx.model.Info.update({
        nickname,
        introduction,
        img_url: imgUrl
      }, {
        where: {
          user_id: userId
        }
      });

      const info = await ctx.model.Info.findOne({
        where: {
          user_id: userId
        }
      })

      ctx.response.body = {
        code: 200,
        data: info,
        msg: 'User information modified successfully !'
      }
    }




  }

  async login() {
    const {
      ctx,
      app
    } = this;

    const {
      username,
      password
    } = ctx.request.body;
    const md5Pass = crypto.createHash('md5').update(password).digest('hex')
    //验证密码

    const user = await ctx.model.User.findOne({
      where: {
        username,
        password: md5Pass
      }
    })

    if (user != null) {
      //查询到用户信息
      const token = await ctx.service.cache.redis.get(user.id) || '';

      const newToken = `Bearer ${app.jwt.sign({
        username,
        id:user.id
      }, app.config.jwt.secret)}`

      if (token == '') {
        //未登录状态
        await ctx.service.cache.redis.set(user.id, newToken, 60 * 60 * 24 * 7, 0);

        ctx.response.body = {
          code: 201,
          data: user,
          msg: 'Login successful !'
        }
      } else {

        //刷新登录状态，该用户之前已经登录
        await ctx.service.cache.redis.set(user.id, newToken, 60 * 60 * 24 * 7, 0);
        ctx.response.body = {
          code: 202,
          data: {
            user,
            Authorization: newToken
          },
          msg: 'Token has been refreshed !'
        }
      }
    } else {

      //账号或密码错误
      ctx.response.body = {
        code: 401,
        data: {},
        msg: 'Incorrect account or password !'
      }
    }



  }

  async sign() {
    const {
      ctx,
      app
    } = this;
    const {
      username,
      password
    } = ctx.request.body;

    //对密码进行加密
    const md5Pass = crypto.createHash('md5').update(password).digest('hex')

    //存储数据
    const user = {
      username,
      password: md5Pass,
      created_at: parseInt(new Date().getTime() / 1000),
      state: 1
    }

    //判断用户名是否被占用
    const isSign = await ctx.model.User.findOne({
      where: {
        username
      }
    })

    if (isSign == null) {
      //创建用户
      const data = await ctx.model.User.create(user);
      //创建用户信息
      const userInfo = await ctx.model.Info.create({
        user_id: data.id,
        nickname: data.username,
        introduction: '您出生了！'
      })

      //生成token
      const token = `Bearer ${app.jwt.sign({
        username:data.username,
        id:data.id
      }, app.config.jwt.secret)}`

      //将token存储到redis,设置失效时间为7天
      const rs = await ctx.service.cache.redis.set(data.id, token, 60 * 60 * 24 * 7, 0); // 存储，失效时间为一周

      ctx.response.body = {
        code: 200,
        data,
        Authorization: token,
        msg: 'login successful !'
      }
    } else {
      ctx.response.body = {
        code: 401,
        msg: 'the user name is taken !',
        data: {}
      }
    }
  }
}

module.exports = HomeController;